/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dawnland03.ui.model.action.handler;

import dawnland03.model.action.Action;
import dawnland03.model.action.handler.HandleStrategy;
import java.util.HashMap;
import java.util.Map;
import javafx.reflect.FXClassType;
import javafx.reflect.FXLocal;
import javafx.reflect.FXLocal.Context;
import javafx.reflect.FXLocal.ObjectValue;
import com.sun.javafx.functions.Function0;
import com.sun.javafx.runtime.Entry;
import dawnland03.model.entity.Entity;

/**
 * @author Petru Obreja (obrejap@yahoo.com)
 */
public class UIHandleStrategy implements HandleStrategy{
    private static HandleStrategy instance;
    private Map<Integer, UIActionHandler> uiActionHandlerMap = new HashMap<Integer, UIActionHandler>(); //key: entityId

    public static HandleStrategy getInstance(){
        if(instance==null){
            instance = new UIHandleStrategy();
        }
        return instance;
    }

    @Override
    public void handle(final Action action) {
        final UIActionHandler uiActionHandler=getUIActionHandler(action.getOwner());
        //this call should be make via an Entry.deferAction(), because it should be run on EDT (Event Dispatch Thread)
        Entry.deferAction(new Function0<Void>() {
            @Override
            public Void invoke() {
               uiActionHandler.handle(action);
                    return null;
                }
            });
    }

    private UIActionHandler getUIActionHandler(Entity entity){
       UIActionHandler uiActionHandler = uiActionHandlerMap.get(entity.getId());
       if(uiActionHandler == null){
           uiActionHandler = createUIActionHandler(entity);
           uiActionHandlerMap.put(entity.getId(), uiActionHandler);
       }
       return uiActionHandler;
    }

    private UIActionHandler createUIActionHandler(Entity entity){
        //load the javaFX class using reflection
        Context context = FXLocal.getContext();
        FXClassType fxClassTypeInstance = context.findClass("dawnland03.ui.model.action.handler.UIActionHandlerImpl");
        ObjectValue objectValue = (ObjectValue)fxClassTypeInstance.newInstance();
        //init the javafx object
        Object obj = objectValue.asObject();
        return (UIActionHandler) obj;
    }
}
